#include "DXTexture.h"
#include "DXEngine.h"
#include <dxerr.h>




CDXTexture::~CDXTexture()
{
	if (m_pMaterial != NULL)
	{
		delete m_pMaterial;
		m_pMaterial = NULL;
	}
	ReleaseCOM(m_pTexture);
}


bool CDXTexture::init(const D3DXMATERIAL tempMaterial)
{
	bool bResult = extractMaterialInfo( tempMaterial);
	return (bResult);
}

void CDXTexture::render()
{
	setTexture();
	setMaterial();
}


bool CDXTexture::extractMaterialInfo(const D3DXMATERIAL tempMaterial)
{
	if (m_pMaterial)
	{
		delete m_pMaterial;
		m_pMaterial = NULL;
	}
	m_pMaterial = new D3DMATERIAL9;
	m_pMaterial->Diffuse = tempMaterial.MatD3D.Diffuse;
	m_pMaterial->Ambient = tempMaterial.MatD3D.Ambient;
	m_pMaterial->Specular = tempMaterial.MatD3D.Specular;
	m_pMaterial->Emissive = tempMaterial.MatD3D.Emissive;
	m_pMaterial->Power = tempMaterial.MatD3D.Power;
	if (tempMaterial.pTextureFilename != NULL)
	{
		if (!extractTextureInfo(tempMaterial.pTextureFilename))
		{
			return false;
		}
	}
	return true;
}

bool CDXTexture::extractTextureInfo(const LPCTSTR filename)
{
	assert(CDXEngine::getInstance()->getD3DDevice() != NULL);
	HRESULT hr = S_OK;
	D3DXIMAGE_INFO srcInfo;
	
	ReleaseCOM(m_pTexture);
	HR( D3DXCreateTextureFromFileExA(CDXEngine::getInstance()->getD3DDevice(),
												filename,
												D3DX_DEFAULT,
												D3DX_DEFAULT,
												m_uiMaxMipmapLevel,
												0,
												D3DFMT_UNKNOWN,
												D3DPOOL_MANAGED,
												D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER,
												D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER,
												D3DCOLOR_ARGB(0, 255, 0, 225),
												&srcInfo,
												NULL,
												&m_pTexture));
	return true;
}

void CDXTexture::setTexture()
{
	assert(CDXEngine::getInstance()->getD3DDevice() != NULL);
	assert(m_pTexture != NULL);

	if (m_pTexture->GetType() == D3DRTYPE_TEXTURE)
	{
		HR(CDXEngine::getInstance()->getD3DDevice()->SetTexture(0, m_pTexture));
	}
}


void CDXTexture::setMaterial()
{
	assert(CDXEngine::getInstance()->getD3DDevice() != NULL);
	assert(m_pMaterial != NULL);

	HR(CDXEngine::getInstance()->getD3DDevice()->SetMaterial(m_pMaterial));
}


void CDXTexture::setMaterialInfo(const D3DMATERIAL9& tempMaterial)
{
	if (m_pMaterial)
	{
		delete m_pMaterial;
		m_pMaterial = NULL;
	}
	m_pMaterial = new D3DMATERIAL9;
	m_pMaterial->Diffuse = tempMaterial.Diffuse;
	m_pMaterial->Ambient = tempMaterial.Ambient;
	m_pMaterial->Specular = tempMaterial.Specular;
	m_pMaterial->Emissive = tempMaterial.Emissive;
	m_pMaterial->Power = tempMaterial.Power;
}